/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.google.common.base.Strings;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.SequenceFlow;
import com.je.bpm.core.model.process.Process;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.engine.history.HistoricActivityInstance;
import com.je.bpm.engine.history.HistoricTaskInstance;
import com.je.bpm.engine.history.HistoricVariableInstance;
import com.je.bpm.engine.impl.HistoricTaskInstanceQueryImpl;
import com.je.bpm.engine.impl.HistoricVariableInstanceQueryImpl;
import com.je.bpm.engine.impl.Page;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.task.GetTakeNodeNameUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取退回节点名称
 */
public class GetGobackAndRetrieveNodeInfoCmd extends NeedsActiveTaskCmd<List<Map<String, String>>> {

    private static final long serialVersionUID = 1L;
    protected String taskId;
    protected String type;

    public GetGobackAndRetrieveNodeInfoCmd(String taskId, String type) {
        super(taskId, null, null);
        this.type = type;
    }

    @Override
    protected List<Map<String, String>> execute(CommandContext commandContext, TaskEntity task) {
        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(task.getProcessDefinitionId());

        Process mainProcess = bpmnModel.getMainProcess();
        String taskKey = task.getTaskDefinitionKey();
        FlowElement flowElement = mainProcess.getFlowElementMap().get(taskKey);
        List<Map<String, String>> result = new ArrayList<>();
        if (flowElement instanceof KaiteBaseUserTask) {
            KaiteBaseUserTask kaiteBaseUserTask = (KaiteBaseUserTask) flowElement;
            if (!type.equals("goBack")) {
                if (task.getVariable(DismissTaskCmd.DISMISS_INFO_KEY) != null && task.getVariable(DismissTaskCmd.DISMISS_INFO_KEY)
                        instanceof Map) {
                    Map<String, Object> dismiss = (Map<String, Object>) task.getVariable(DismissTaskCmd.DISMISS_INFO_KEY);
                    if (dismiss != null) {
                        Object currentNodeDisMiss = dismiss.get(taskKey);
                        if (currentNodeDisMiss != null && currentNodeDisMiss instanceof Map) {
                            Map<String, Object> currentNodeDisMissInfo = (Map<String, Object>) currentNodeDisMiss;
                            String nodeName = (String) currentNodeDisMissInfo.get("nodeName");
                            FlowElement userTask = bpmnModel.getMainProcess().getFlowElement((String) currentNodeDisMissInfo.get("nodeId"));
                            if (Strings.isNullOrEmpty(nodeName)) {
                                String takeNodeName = GetTakeNodeNameUtil.builder().getTakeNodeName(flowElement);
                                nodeName = takeNodeName;
                            }
                            String nodeId = (String) currentNodeDisMissInfo.get("nodeId");
                            Map<String, String> dismissMap = new HashMap<>();
                            dismissMap.put("nodeId", nodeId);
                            dismissMap.put("nodeName", nodeName);
                            result.add(dismissMap);
                            return result;
                        }
                    }
                }
            }

            String dismissNodeId = "";
            //如果不是驳回的话，正常获取历史最近的一个，如果有两个入线，驳回到当前节点，再退回
            if (task.getVariable(DismissTaskCmd.DISMISS_INFO_KEY) != null && task.getVariable(DismissTaskCmd.DISMISS_INFO_KEY)
                    instanceof Map) {
                Map<String, Object> dismiss = (Map<String, Object>) task.getVariable(DismissTaskCmd.DISMISS_INFO_KEY);
                if (dismiss != null) {
                    Object currentNodeDisMiss = dismiss.get(taskKey);
                    if (currentNodeDisMiss != null && currentNodeDisMiss instanceof Map) {
                        Map<String, Object> currentNodeDisMissInfo = (Map<String, Object>) currentNodeDisMiss;
                        dismissNodeId = (String) currentNodeDisMissInfo.get("nodeId");

                    }
                }
            }
            //获取节点的进线
            List<SequenceFlow> list = kaiteBaseUserTask.getIncomingFlows();
            List<SequenceFlow> listRel = new ArrayList<>();
            if (!Strings.isNullOrEmpty(dismissNodeId)) {
                for (SequenceFlow sequenceFlow : list) {
                    if (!dismissNodeId.equals(sequenceFlow.getSourceRef())) {
                        listRel.add(sequenceFlow);
                    }
                }
            }
            if (listRel.isEmpty()) {
                listRel = list;
            }
            //获取历史最近的一个
            List<HistoricActivityInstance> historicActivityInstanceList = commandContext.getProcessEngineConfiguration().getHistoryService().createHistoricActivityInstanceQuery().processInstanceId(task.getProcessInstanceId())
                    .orderByHistoricActivityInstanceStartTime().desc().list();
            for (HistoricActivityInstance historicActivityInstance : historicActivityInstanceList) {
                for (SequenceFlow sequenceFlow : listRel) {
                    if (sequenceFlow.getSourceRef().equals(historicActivityInstance.getActivityId())) {
                        FlowElement userTask = bpmnModel.getMainProcess().getFlowElement(sequenceFlow.getSourceRef());
                        if (userTask != null) {
                            result.add(getNodeInfo(commandContext, task.getProcessInstanceId(), userTask));
                            break;
                        }
                    }
                }
            }
        }
        return result;
    }

    private Map<String, String> getNodeInfo(CommandContext commandContext, String piid, FlowElement userTask) {
        Map<String, String> nodeInfo = new HashMap<>();
        HistoricTaskInstanceQueryImpl historicTaskInstanceQuery = new HistoricTaskInstanceQueryImpl();
        historicTaskInstanceQuery.processInstanceId(piid);
        historicTaskInstanceQuery.taskDefinitionKey(userTask.getId());
        historicTaskInstanceQuery.orderByTaskCreateTime().desc();
        List<HistoricTaskInstance> links = commandContext.getProcessEngineConfiguration().getHistoricTaskInstanceEntityManager()
                .findHistoricTaskInstancesByQueryCriteria(historicTaskInstanceQuery);
        if (links.size() == 0) {
            return nodeInfo;
        }
        nodeInfo.put("directTaskId", userTask.getId());
        if (Strings.isNullOrEmpty(userTask.getName())) {
            String takeNodeName = GetTakeNodeNameUtil.builder().getTakeNodeName(userTask);
            nodeInfo.put("directTaskName", takeNodeName);
        } else {
            nodeInfo.put("directTaskName", userTask.getName());
        }
        String prevAssignee = "";
        KaiteBaseUserTask kaiteBaseUserTask = (KaiteBaseUserTask) userTask;
        if (kaiteBaseUserTask.hasMultiInstanceLoopCharacteristics()) {
            Page page = new Page(0, 10);
            HistoricVariableInstanceQueryImpl historicVariableInstanceQuery = new HistoricVariableInstanceQueryImpl();
            historicVariableInstanceQuery.processInstanceId(piid);
            historicVariableInstanceQuery.variableName("datas");
            historicVariableInstanceQuery.executionId(links.get(0).getExecutionId());
            List<HistoricVariableInstance> historicVariableInstanceList = commandContext.getProcessEngineConfiguration()
                    .getHistoricVariableInstanceEntityManager().
                            findHistoricVariableInstancesByQueryCriteria(historicVariableInstanceQuery, page);
            if (historicVariableInstanceList.size() > 0) {
                Object value = historicVariableInstanceList.get(0).getValue();
                if (value instanceof ArrayList) {
                    List<String> userIds = (List<String>) value;
                    prevAssignee = userIds.stream().collect(Collectors.joining(","));
                }
            }
        } else {
            prevAssignee = links.get(0).getAssignee();
        }
        nodeInfo.put("prevAssignee", prevAssignee);
        return nodeInfo;
    }

}
